package com.chenfan.finance.config.sharding;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * @author Eleven.Xiao
 * @description // 淘系数据订单数据分表的自定义规则类(范围)
 * @date 2020/12/22 14:15
 */
public class TocOrderTableRangeShardingAlgorithm extends CommonShardDataBase implements RangeShardingAlgorithm<LocalDateTime> {
    protected static final DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
                                         RangeShardingValue<LocalDateTime> rangeShardingValue) {
        Range<LocalDateTime> ranges = rangeShardingValue.getValueRange();

        LocalDateTime start = ranges.lowerEndpoint();
        LocalDateTime end = ranges.upperEndpoint();


        int startYear = start.getYear();
        int endYear = end.getYear();

        int startMonth = start.getMonthValue();
        int endMonth = end.getMonthValue();

        Collection<String> tables = new LinkedHashSet<>();
        if (start.getNano() <= end.getNano()) {
            for (String c : availableTargetNames) {
                int cMonth = Integer.parseInt(c.substring(c.length() - 6));
                if (cMonth >= Integer.parseInt("" + startYear + startMonth) && cMonth <= Integer.parseInt("" + endYear + endMonth)) {
                    tables.add(c);
                }
            }
        }
        return tables;
    }
}
